package notif.settings.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.google.storage.onestore.v3.OnestoreEntity.User;

import notif.settings.model.Todo;

public enum Dao {
  INSTANCE;

  public List<Todo> listTodos() {
    EntityManager em = EMFService.get().createEntityManager();
    // Read the existing entries
    Query q = em.createQuery("select m from Todo m");
    List<Todo> todos = q.getResultList();
    return todos;
  }

  public void add(String userId, String jobtitle, String companies,
      String zipcode, String deviceid) {
    synchronized (this) {
      EntityManager em = EMFService.get().createEntityManager();
      Todo todo = new Todo(userId, jobtitle, companies, zipcode, deviceid);
      em.persist(todo);
      em.close();
    }
  }
  
  public void update(String jobtitle, String companies, String zipcode, String deviceid){
	  synchronized (this) {
	      EntityManager em = EMFService.get().createEntityManager();
	      Query q = em.createQuery("select m from Todo m where m.author = :userId");
	      List<Todo> todos = q.getResultList();
	      q.setParameter("jobtitle", jobtitle);
	      q.setParameter("companies", companies);
	      q.setParameter("zipcode", zipcode);
	      q.setParameter("deviceid", deviceid);
	      em.persist(todos);
	      em.close();
	    }
	  
  }

  public List<Todo> getTodos(String userId) {
    EntityManager em = EMFService.get().createEntityManager();
    Query q = em
        .createQuery("select t from Todo t where t.author = :userId");
    q.setParameter("userId", userId);
    List<Todo> todos = q.getResultList();
    return todos;
  }

  public void remove(long id) {
    EntityManager em = EMFService.get().createEntityManager();
    try {
      Todo todo = em.find(Todo.class, id);
      em.remove(todo);
    } finally {
      em.close();
    }
  }
} 
